using System.Collections.Generic;
using UnityEngine;



namespace MyUtility.Utility
{
    public static class RandomUtils
    {
        public static RandWeightItem? GetRandWeight(List<RandWeightItem> items, int allWeight)
        {
            if (items == null || items.Count == 0)
            {
                Debug.LogError("传入列表参数为空！");
                return null;
            }

            var randVal = Random.Range(0, allWeight);
            foreach (var item in items)
            {
                randVal -= item.Weight;
                if (randVal < 0)
                {
                    return item;
                }
            }

            return null;
        }


        /// <summary>
        /// 必定会随机一个权重条目出来
        /// </summary>
        /// <param name="items">  </param>
        /// <returns></returns>
        public static RandWeightItem? GetRandWeight(List<RandWeightItem> items)
        {
            if (items == null || items.Count == 0)
            {
                Debug.LogError("传入列表参数为空！");
                return null;
            }

            var allWeight = 0;
            items.ForEach(it => { allWeight += it.Weight; });

            var item = GetRandWeight(items, allWeight);
            return item;
        }


    }

    /// <summary>
    /// 随机权重条目
    /// </summary>
    public struct RandWeightItem
    {
        /// <summary>
        /// 索引
        /// </summary>
        public int Index;
        /// <summary>
        /// 数值
        /// </summary>
        public int Value;
        /// <summary>
        /// 权重
        /// </summary>
        public int Weight;
    }

}